﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Gazer.cs" company="R.V.Kasner">
//   Copyright © 2011 R.V.Kasner
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace Owen.Core.Services
{
    using System;
    using System.Text;

    public sealed class Gazer : IGazer
    {
        private readonly StringBuilder stringBuilder;

        private readonly IDateTimeService dateTimeService;

        public Gazer(IDateTimeService dateTimeService)
        {
            if (dateTimeService == null)
            {
                throw new ArgumentNullException("dateTimeService");
            }

            this.dateTimeService = dateTimeService;
            this.stringBuilder = new StringBuilder();
        }
        
        public event Action<string> Changed;
        
        public void Append(string entry)
        {
            this.AppendDate();
            this.stringBuilder.Append(entry);
            this.RaiseChanged();
        }

        public void Append(string formatEntry, params object[] data)
        {
            this.AppendDate();
            this.stringBuilder.AppendFormat(formatEntry, data);
            this.RaiseChanged();
        }

        public void Clear()
        {
            this.stringBuilder.Clear();
            this.RaiseChanged();
        }

        private void AppendDate()
        {
            var dt = this.dateTimeService == null ? new DateTime(0) : this.dateTimeService.GetDateTimeNow();
            this.stringBuilder.Append(Environment.NewLine);
            this.stringBuilder.Append(Environment.NewLine);
            this.stringBuilder.Append(dt.ToString("HH:mm:ss.ff"));
            this.stringBuilder.Append("   ");
        }

        private void RaiseChanged()
        {
            Action<string> handler = this.Changed;
            if (handler != null)
            {
                handler(this.stringBuilder.ToString());
            }
        }
    }
}